import json
from lxml import etree
import openai
import requests
import threading
import time
import urllib
import uuid
import websocket

# 配置敏感信息
apikey = '您的ChatGPT的APIkey' #如sk-BWDog51x2aand3345332wdswqqMZUYnAMIDMgpQxybOBqo83pKxs3
apiurl = '您的ChatGPT的APIkey' #如：https://chatapi.onechats.top/v1
url = '您的聊天网站地址' #如：lcim.guozhufeng.com
rguser = '您的机器人用户名' #如：XiaoLingAI
rguserPassword = '您的机器人的密码' #如：@abc123456
rggroupID = '接入群组ID'  #如：121

def ai(message):
    client = openai.OpenAI(
        api_key=apikey,
        base_url=apiurl
    )
    chat_completion = client.chat.completions.create(
        messages=[
            {
                'role': 'system',
                'content': '你是由凌红科技开发的一款AI软件，请以中文回答我的问题。'
            },
            {
                'role': 'user',
                'content': message,
            }
        ],
        model='gpt-4o-mini',
    )
    return chat_completion.choices[0].message.content

def login():
    print('登录')
    headers = {'accept': 'application/json, text/plain, */*',
               'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'}
    response = json.loads(requests.post(f'https://{url}/common/pub/login', headers=headers, data=f'account={rguser}&password={rguserPassword}&code=').text)
    session = response['data']['sessionId']
    token = response['data']['authToken']
    userid = response['data']['userInfo']['user_id']
    with open('./session', 'w') as f:
        f.write(session)
    with open('./token', 'w') as f:
        f.write(token)
    with open('./userid', 'w') as f:
        f.write(str(userid))

def exp():
    token = open('./token').read()
    session = open('./session').read()
    headers = {'accept': 'application/json, text/plain, */*',
               'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
               'authorization': token,
               'cookie': 'PHPSESSID=' + session}
    rsp = json.loads(requests.post(f'https://{url}/enterprise/im/getContacts', headers=headers).text)
    if rsp['code'] != 0 or rsp['msg'] != '':
        print('自动过期')
        print(rsp['msg'])
        login()

def run():
    print('进入主线程')

    def on_open(ws):
        print('连接成功')
        threading.Thread(target=on_ping, args=(ws,)).start()

    def on_message(ws, message):
        message = json.loads(message)
        print(message)
        if message['type'] == 'init':
            userid = int(open('./userid').read())
            token = open('./token').read()
            ws.send(json.dumps({'type': 'bindUid', 'user_id': userid, 'token': token}))
            print({'type': 'bindUid', 'user_id': userid, 'token': token})
            token = open('./token').read()
            session = open('./session').read()
            headers = {'accept': 'application/json, text/plain, */*',
                       'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
                       'authorization': token,
                       'cookie': 'PHPSESSID=' + session,
                       'sessionid': session}
            print(json.loads(requests.post(f'https://{url}/common/pub/bindUid', data='client_id=' + message['client_id'] + '&user_id=' + open('./userid').read(), headers=headers).text))
            print(json.loads(requests.post(f'https://{url}/enterprise/files/index', data='page=1&limit=20&keywords=&cate=0&is_all=0&role=0', headers=headers).text))
        elif message['type'] == 'isOnline':
            pass
        elif message['type'] == 'undoMessage':
            pass
        elif message['type'] == 'ping':
            ws.send('{"type":"pong"}')
        elif message['type'] == 'pong':
            pass
        elif message['type'] == 'simple':
            print('simplemessage')
        elif message['type'] == 'group' and message['data']['type'] == 'text' and str(message['data']['fromUser']['id']) != open('./userid').read():
            if message['data']['toContactId'] == f'group-{rggroupID}':
                exp()
                print(message['data']['content'])
                tree = etree.HTML(message['data']['content'])
                question = [element.text for element in tree.xpath('//span')]
                question = '\n'.join(question)
                print(question)
                answer = ai(question)
                print(answer)
                token = open('./token').read()
                session = open('./session').read()
                headers = {
                    'accept': 'application/json, text/plain, */*',
                    'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
                    'authorization': token,
                    'cookie': 'PHPSESSID=' + session,
                    'sessionid': session,
                    'Host': url,
                    'Connection': 'keep-alive'
                }

                data = 'id=' + str(uuid.uuid1()) + '&type=text&status=going&sendTime=' + str(int(time.time() * 1000)) + f'&toContactId=group-{rggroupID}&fromUser%5Bid%5D=980&fromUser%5BdisplayName%5D=%E5%B0%8F%E5%87%8CAI&fromUser%5Bavatar%5D=https%3A%2F%2F'+url+'%2Favatar%2F%E5%B0%8F%E5%87%8CAI%2F80%2F960&fromUser%5Baccount%5D='+rguser+'&content=' + urllib.parse.quote(answer) + '&is_group=1'
                a = requests.post(f'https://{url}/enterprise/im/sendMessage', data=data, headers=headers)
            else:
                print('Other group:', message['data']['toContactId'])
        else:
            pass

    def on_error(ws, error):
        exp()
        print(error)

    def on_close(ws):
        exp()
        print('断线重连中...')
        time.sleep(5)
        connect()

    def on_ping(ws):
        try:
            while True:
                time.sleep(15)
                ws.send('{"type":"ping"}')
        except:
            pass

    def connect():
        exp()
        ws = websocket.WebSocketApp(f'wss://{url}/wss', cookie='PHPSESSID=' + open('./session').read(), on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close)
        ws.run_forever()

    connect()

def console():
    while True:
        command = input().split(' ')
        if command[0] == 'kick':
            pass
        elif command[0] == 'delete':
            pass
        elif command[0] == 'say':
            del command[0]
            userid = int(open('./userid').read())
            token = open('./token').read()
            session = open('./session').read()
            headers = {
                'accept': 'application/json, text/plain, */*',
                'accept-language': 'zh-CN,zh;q=0.9',
                'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'cache-control': 'no-cache',
                'authorization': token,
                'cookie': 'PHPSESSID=' + session,
                'sessionid': session,
                'Host': url,
                'Connection': 'keep-alive'
            }
            data = 'id=' + str(uuid.uuid1()) + '&type=text&status=going&sendTime=' + str(int(time.time() * 1000)) + f'&toContactId=group-{rggroupID}&fromUser%5Bid%5D=980&fromUser%5BdisplayName%5D=%E5%B0%8F%E5%87%8CAI&fromUser%5Bavatar%5D=https%3A%2F%2F'+url+'%2Favatar%2F%E5%B0%8F%E5%87%8CAI%2F80%2F960&fromUser%5Baccount%5D='+rguser+'&content=' + urllib.parse.quote(' '.join(command)) + '&is_group=1'
            requests.post(f'https://{url}/enterprise/im/sendMessage', data=data, headers=headers)

# threading.Thread(target=run).start()
# threading.Thread(target=console).start()
run()
